/**
 * 词典抓取器, 被fetchWorker调用
 * */
var request = require('request');
var config = require('../config.json');

function getMeaningsAndProperties(explain) {
  var start = explain.indexOf('.');
  return {
    property: explain.substring(0, start),
    meaning: explain.substring(start + 1, explain.length).trim()
  }
}

function generateUniqueValues(dataArray) {
  var tempArr = dataArray.join(',').split(/(,|;|，|；)/);
  var recorder = {};
  var result = '';
  for (var i = 0; i < tempArr.length; i++) {
    if (tempArr[i].search(/(,|;|，|；)/) === -1 && tempArr[i].trim() !== '')
      recorder[tempArr[i].trim()] = true;
  }
  for (var j in recorder) {
    result += ',' + j.trim();
  }
  return result === '' ? result : result.substring(1);
}

function handleRawResult(word, result) {
  var explains = result.basic.explains;
  var meaningArray = [];
  var propertyArray = [];
  try {
    for (var i = 0; i < explains.length; i++) {
      var handleResult = getMeaningsAndProperties(explains[i]);
      propertyArray.push(handleResult.property);
      meaningArray.push(handleResult.meaning);
    }
  } catch (e) {
    console.error(e);
    console.log('![---' + word + '---]');
  }
  return {
    word: word,
    phonetic: {
      default: result.basic.phonetic,
      usPhonetic: result.basic['us-phonetic'],
      ukPhonetic: result.basic['uk-phonetic']
    },
    outline: result.translation[0],
    meanings: generateUniqueValues(meaningArray),
    properties: generateUniqueValues(propertyArray),
    explains: result.basic.explains
  }
}

function isValidResult(resultObj) {
  return resultObj.translation.length > 0 &&
    resultObj.errorCode === 0 && resultObj.basic &&
    resultObj.basic.explains && resultObj.basic.explains.length > 0
}

module.exports = function (word, callback) {
  var query = config.dictApi + word;
  request.get(query, function (err, data) {
    try {
      var resultObj = JSON.parse(data.body);
      if (isValidResult(resultObj)) {
        callback(handleRawResult(word, resultObj));
      } else {
        throw new Error('ERROR Translate: ' + word);
      }
    } catch (e) {
      console.error(e);
      console.log('![---' + word + '---]');
      callback(null);
    }
  });
};
